package com.codejiwei.flink.mongodb;

import com.google.gson.Gson;
import com.mongodb.MongoClient;
import com.mongodb.MongoClientOptions;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.MongoIterable;
import org.bson.Document;

import java.util.Arrays;

/**
 * @author jiwei
 * @description
 * @date 2023/9/11 9:55
 */
public class MongoDBTest {
    public static void main(String[] args) {

        Gson gson = new Gson();


        MongoCredential credential = MongoCredential.createCredential("datacube_test", "db_datacube_test", "n_LFvg0Z".toCharArray());
//        MongoClient client = new MongoClient(new ServerAddress("192.168.102.154", 27017), credential, getOptions(10000).build());
        MongoClient client = new MongoClient(new ServerAddress("192.168.102.154", 27017), Arrays.asList(credential));
        System.out.println("Connect to database successfully");

        MongoIterable<String> dbs = client.listDatabaseNames();
        for (String db : dbs) {
            System.out.println("===============" + db);
        }

        MongoDatabase db = client.getDatabase("db_datacube_test");
        MongoCollection<Document> types = db.getCollection("types");

        for (Document document : types.find()) {
            String json = document.toJson();
            Type type = gson.fromJson(json, Type.class);
            System.out.println("----------------" + document);
            System.out.println("================" + json);
            System.out.println("----------------" + type);
        }



//        MongoClient client = new MongoClient(new MongoClientURI("mongodb://datacube_test:n_LFvg0Z@192.168.102.154:27017/db_datacube_test", getOptions(10000)));
//        for (String listDatabaseName : client.listDatabaseNames()) {
//            System.out.println(listDatabaseName);
//        }

    }
    public static MongoClientOptions.Builder getOptions(int maxConnectionIdleTime) {
        MongoClientOptions.Builder builder = new MongoClientOptions.Builder();
        builder.maxConnectionIdleTime(maxConnectionIdleTime);
        return builder;
    }
}
